package com.atguigu.tingshu.order.receiver;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * @author atguigu-mqx
 * @ClassName OrderReceiver
 * @description: TODO
 * @date 2024年10月10日
 * @version: 1.0
 */
@Slf4j
@Component
public class OrderReceiver {

    @Autowired
    private OrderInfoService orderInfoService;


    /**
     * 订单支付成功
     * @param orderId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER_PAY_SUCCESS, durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ORDER),
            key = MqConst.ROUTING_ORDER_PAY_SUCCESS
    ))
    public void orderPaySuccess(String orderNo, Message message, Channel channel) {
        try {
            //  判断
            if (!StringUtils.isEmpty(orderNo)){
                //  调用服务层方法
                orderInfoService.updateOrderStatus(orderNo);
                //  orderPaySuccess

            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }


    /**
     * 取消订单
     *
     * @param orderNo
     * @param message
     * @param channel
     */
    @RabbitListener(queues = MqConst.QUEUE_CANCEL_ORDER)
    public void cancelOrder(String orderNo, Message message, Channel channel) {
        //    获取到订单编号
        log.info("取消订单，订单编号：{}", orderNo);
        try {
            if (!StringUtils.isEmpty(orderNo)) {
                //  调用取消订单方法.
                orderInfoService.cancelOrder(orderNo);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            log.error("取消订单失败"+e.getMessage());
        }
        //  手动ack
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
